﻿using LogLib;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Security.Principal;
using System.Text;

namespace PipeClient
{
    public class Pipe
    {
        public int id { get; private set; }

        private string ServerName = "MainStartup";

        //private string ServerName = "";

        public const int ClientConnectTimeout = 3000;

        public string SendMessage { get; set; }

        public Pipe(int id, string msg, string server)
        {
            ServerName = server;
            this.id = id;
            SendMessage = msg;
        }

        public Pipe(int id, string msg)
        {
            this.id = id;
            SendMessage = msg;
        }

        public void run()
        {
            try
            {
                using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(
                    ".",
                    ServerName,
                    PipeDirection.InOut,
                    PipeOptions.None,
                    TokenImpersonationLevel.None))
                {
                    //连接服务端
                    pipeClient.Connect(ClientConnectTimeout);
                    StreamWriter sw = new StreamWriter(pipeClient);
                    StreamReader sr = new StreamReader(pipeClient);
                    //Log.WriteAsync(string.Format("Client {0} SendMessage: {1}", id, SendMessage));
                    sw.WriteLine(SendMessage);
                    sw.Flush();
                    string reponse = sr.ReadLine();
                    //Log.WriteAsync(string.Format("Client {0} ReceiveMessage: {1}", id, reponse));
                    if (!pipeClient.IsConnected)
                    {
                        //Log.WriteAsync("Pipe is Broken");
                    }
                    else
                    {
                        pipeClient.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(ex.ToString());
            }
            //Log.WriteAsync(string.Format("Client {0} end of conversation", id));
        }
    }
}
